package com.solocredit.finance.ui.steps.impl

import android.content.Context
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.steps.view.IMullaStepsView
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.utils.language.LocaleContract
import com.solocredit.finance.utils.language.MultiLanguages
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/4 15:46
 * @Annotation：认证流程列表 Presenter 实现
 */
class MullaStepsPresenterImpl(context: Context?) : MvpPresenter<IMullaStepsView>(context) {

    //流程步骤数据
    private var stepData: JSONObject? = null
    //记录当前进行中步骤的Title
    private var curtStepTitle = ""

    /**
     * 获取全部流程
     */
    fun loadMullaProcessStepAction(){
        val stepString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PROCESS)
        if (stepString.isNotEmpty()){
            stepData = JSONObject(stepString)
            stepData?.let {  data ->
                val allStepTitles = data.optJSONArray("allStepTitles")
                //当前进行的步骤
                val curtIndex = getMullaStepIndex()

                allStepTitles?.let { allTitles ->
                    //设置流程进度
                    mvpView?.showMullaStepsProgress(allTitles.length(),curtIndex+1)
                }
                //移除所有的流程步骤
                mvpView?.removeMullaStepAllViews()

                allStepTitles?.let {
                    for (i in 0 until it.length()) {
                        var stepTitle = it.optString(i)
                        stepTitle = getMullaShowStepTitle(stepTitle)

                        if (i < curtIndex){//已完成
                            mvpView?.addMullaStepAfterView(stepTitle)
                        } else if (i == curtIndex){//正在进行
                            curtStepTitle = stepTitle
                        } else {//未开始
                            mvpView?.addMullaStepBeforeView(stepTitle)
                        }
                    }
                }
            }
            //设置所有步骤列表
            showMullaStepPage()
        }
    }

    /**
     * 提交数据
     */
    fun onMullaSubmitProcessAction(path: String,params: JSONObject){
        val httpUrl = ApiService.getHttpUrl(path)
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.hideMullaLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView?.showMullaSubmitSuccess()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.hideMullaLoading()
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showFlexiMolaNetworkErrorDialog("Step Page Submit: $path", onRetryClick = {
                        mvpView?.showMullaLoading()
                        onMullaSubmitProcessAction(path,params)
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 根据Step类型显示不同的Page
     */
    private fun showMullaStepPage(){
        stepData?.let { data ->
            val allStepTitles = data.optJSONArray("allStepTitles")

            //当前进行的步骤
            val curtIndex = getMullaStepIndex()
            val allSteps = data.optJSONArray("allSteps")
            var eventTitle = ""
            allSteps?.let {
                eventTitle = it.optString(curtIndex)
            }

            var stepTitle = ""
            allStepTitles?.let {
                if (curtIndex == it.length()){//所有步骤已完成
                    mvpView?.showMullaStepsCompletePage()
                    return
                }
                stepTitle = it.optString(curtIndex)
            }

            stepTitle = getMullaShowStepTitle(stepTitle)
            //获取对应的key
            val curtKey = allSteps?.optString(curtIndex)
            //Contact 类型
            if (data.has(curtKey)){
                val item = data.optJSONObject(curtKey)
                item?.let {
                    it.put("showTitle",stepTitle)
                    it.put("stepTitle",eventTitle)
                    if (it.has("isContact") && it.optString("isContact") == "YES"){
                        mvpView?.showMullaStepContactPage(it)
                        return
                    }
                }
            }

            curtKey?.let {
                //todo Ocr证件照样式
                if (it.contains("ocr_info")){
                    val stepData = JSONObject()
                    stepData.put("showTitle",stepTitle)
                    stepData.put("stepTitle",eventTitle)
                    mvpView?.showMullaStepOcrPage(stepData)
                    return
                }

                //todo Selfie自拍照样式
                if (it.contains("sefie_info")){
                    val stepData = JSONObject()
                    stepData.put("showTitle",stepTitle)
                    stepData.put("stepTitle",eventTitle)
                    mvpView?.showMullaStepSelfiePage(stepData)
                    return
                }

                //todo Account账户样式（法语地区绑定账号）
                if (it.contains("account_info") && MullaConfigs.isFrench()){
                    val stepData = JSONObject()
                    stepData.put("showTitle",stepTitle)
                    stepData.put("stepTitle",eventTitle)
                    mvpView?.showMullaStepAccountPage(stepData)
                    return
                }
                //常规通用样式
                if (data.has(curtKey)){
                    data.optJSONObject(curtKey)?.let { item ->
                        item.put("showTitle",stepTitle)
                        item.put("stepTitle",eventTitle)
                        mvpView?.showMullaStepCommonPage(item)
                    }
                }
            }
        }
    }

    /**
     * 获取当前步骤的title
     */
    fun loadMullaCurrentStepTitle(): String{
        return curtStepTitle
    }

    /**
     * 获取当前显示title
     */
    private fun getMullaShowStepTitle(stepItem: String): String{
        //是否是坦桑地区,需要根据语言显示
        if (MullaConfigs.isTanz()){
            val stepTitleItem = JSONObject(stepItem)
            val curtLocale = MultiLanguages.getAppLanguage(mvpView?.getContext())
            return when(curtLocale.language){
                LocaleContract.getSwahiliLocale().language -> {//坦桑
                    stepTitleItem.optString("sw")
                }
                else -> {
                    stepTitleItem.optString("en")
                }
            }
        }
        return stepItem
    }

    /**
     * 获取 steps 中第一个在步骤在总步骤中是第几个
     */
    private fun getMullaStepIndex(): Int{
        var index = 0
        stepData?.let { data ->
            val allStepTitles = data.optJSONArray("allStepTitles")
            allStepTitles?.let { allTitles ->
                index = allTitles.length()
            }

            //剩余未完成步骤
            val steps = data.optJSONArray("steps")
            steps?.let {
                if (it.length() == 0){//已完成
                    return index
                }
            }
            //总步骤
            val allSteps = data.optJSONArray("allSteps") ?: return index

            //当前进行的步骤
            steps?.let {
                val curtStep = it.optString(0)
                for (i in 0..<allSteps.length()){
                    if (curtStep == allSteps.optString(i)){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 复制主产品信息到目标产品
     */
    fun onMullaCopyMainProductToChildProductAction(targetProduct: String){
        mvpView?.showMullaLoading()
        val params = JSONObject()
            .addCommonParams()
            .addRandomParams()
            .apply {
                put("sourceProduct", MullaConfigs.MULLA_APPNAME)
                put("targetProduct", targetProduct)
            }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_LOAN_PRODUCT_COPY_PATH)
        HttpHelper.postMullaAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        var pToken = ""
                        if (obj != null){
                            pToken = obj.optString("token","")
                        }
                        if (pToken.isNotEmpty()){
                            MullaConfigs.clickProductToken = pToken
                        }
                        //进入申贷页
                        mvpView?.showMullaApplyPage()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}